﻿class com.dmotiko.util.XMLUtils {
	
	public static function getNodeByName(xml:XMLNode, name:String, validator:Array):XMLNode {
		for ( var i:Number = 0; i < xml.childNodes.length; i++) {
			if ( xml.childNodes[i].nodeName == name) return xml.childNodes[i];
		}
		return undefined;
	}
	
	public static function getNodesByName(xml:XMLNode, name:String, validator:Object):Array {
		var aNodes:Array = new Array();
		for ( var i:Number = 0; i < xml.childNodes.length; i++) {
			if ( xml.childNodes[i].nodeName == name) {
				var bCheck:Boolean = false;
				for ( var s:String in validator) {
					bCheck = xml.childNodes[i].attributes[s] != validator[s] || bCheck;
				}
				if(!bCheck) aNodes.push( xml.childNodes[i] );
			}
		}
		return aNodes;
	}
	
	public static function node2object( xml:XMLNode ):Object {
		var o:Object = xml.attributes;
		o.nodeName = xml.nodeName;
			
		for (var i:Number = 0; i < xml.childNodes.length ; i++) {
			var node:XMLNode = xml.childNodes[i]; 
			if ( !node.nodeName ) {
				o.XMLcontent = node.toString();
			} else {
				if (! o[node.nodeName] ) o[node.nodeName] = new Array();
				o[node.nodeName].push( node2object( node ) );
			}
		}
		/*
		for ( var s in o) {
			if (o[s] instanceof Array && o[s].length == 1) o[s] = o[s][0];
		}
		*/
		return o;
	}
	
}